#include "video.h"

/*
 * 
 * Video: Constructor
 */
Video::Video()
{
  
}

/*
 * 
 * ~Video: Destructor
 */
Video::~Video()
{
}

/*
 * 
 * freeMemory: Frees class memory
 * @param N/A
 * @return void
 */
void Video::freeMemory()
{    

  	if(m_pScreen)
 	{
	  SDL_FreeSurface (m_pScreen);
	}
  	SDL_Quit();
  
  	m_pLog->debug("- Video");
	m_pLog=NULL;
}				
 	
/*
 * 
 * init: Initializes video. SDL window and OpenGL inside.
 * @param _windowName: Name of the window
 * @param _width: Width of the screen/window
 * @param _height: Height of the screen/window.
 * @param _fullScreen: Fullscreen video?
 * @return bool: True when initialization goes OK 
 */
bool Video::init(const char _windowName[63],
                  int _width,
                  int _height, 
                  int _fullScreen)
{  
  const SDL_VideoInfo *videoInfo;
  int videoFlags;
  
  m_pLog=&Log::getInstance();
  /*-----------------------------------------
    SDL initialization
  -----------------------------------------*/
  if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_TIMER))
  {
    m_pLog->error("SDL_Init");
    return false;
  }   
  
    videoInfo = SDL_GetVideoInfo( );

    if ( !videoInfo )
    {
      m_pLog->error("SDL_GetVideoInfo");
      return false;
  }
  
  videoFlags  = SDL_OPENGL;          /* Enable OpenGL in SDL */
    videoFlags |= SDL_GL_DOUBLEBUFFER; /* Enable double buffering */
    videoFlags |= SDL_HWPALETTE;       /* Store the palette in hardware */
    videoFlags |= SDL_RESIZABLE;       /* Enable window resizing */

  // Comprobamos si se puede usar la memoria para guardar surfaces
  // FIX: Problema de parpadeo con SDL_HWSURFACE
  if ( videoInfo->hw_available )
    //videoFlags |= SDL_HWSURFACE;
	videoFlags |= SDL_SWSURFACE;
  else
    videoFlags |= SDL_SWSURFACE;
    
  // El blit puede hacerse por HW?
    if ( videoInfo->blit_hw )
    videoFlags |= SDL_HWACCEL;

  SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

  m_pScreen = SDL_SetVideoMode (_width, _height, 16, videoFlags);
  
  if (m_pScreen == NULL)
  {
    m_pLog->error("SetVideoMode");
    return false;
  } 
      
  SDL_WM_SetCaption (_windowName, NULL);
  
  if(_fullScreen){
    SDL_WM_ToggleFullScreen (m_pScreen);
	}
  
  //-----------------------------------------
  //OpenGL initialization
  //-----------------------------------------
	glEnable(GL_TEXTURE_2D);
	glShadeModel( GL_SMOOTH );    
	glClearColor( 0.5f, 0.5f, 0.5f, 1.0f );    
	glMatrixMode (GL_PROJECTION);
	glLoadIdentity ();
	glOrtho (0, WIDTH, HEIGHT, 0, -1, 1);
	glMatrixMode (GL_MODELVIEW);
	glEnable( GL_BLEND );
	glBlendFunc( GL_SRC_ALPHA, GL_ONE );
	glDepthFunc (GL_ALWAYS);	
  	m_pLog->debug("+ Video"); 
  	return true;
}

/*
 * 
 * update: Updates screen
 * @param N/A
 * @return void
 */
void Video::update()
{
  SDL_GL_SwapBuffers();
}
